<template>
  <div v-my-directive="'stuId2'">app</div>
  <button v-tooltip="'点击该按钮进行表单提交'">提交</button>
</template>

<script setup>
const vMyDirective = {
  mounted(el, binding) {
    el.id = binding.value;
    el.style.color = "red";
    if (binding.value === "stuId") {
      el.classList.add("active");
    } else {
      el.classList.remove("active");
    }
  },
  getSSRProps(binding) {
    if (binding.value === "stuId") {
      return {
        id: binding.value,
        style: { color: "red" },
        class: "active",
      };
    } else {
      return {
        id: binding.value,
        style: { color: "red" },
      };
    }
  },
};

const vTooltip = {
  mounted(el, binding) {
    const showTooltip = () => {
      const tooltip = document.createElement("div");
      tooltip.innerText = binding.value;
      // 下面就是一些 DOM 操作
      // 1. 基本的样式
      Object.assign(tooltip.style, {
        position: "absolute",
        backgroundColor: "rgba(0, 0, 0, 0.75)",
        color: "white",
        padding: "4px 8px",
        borderRadius: "4px",
        fontSize: "12px",
        pointerEvents: "none",
        zIndex: 1000,
      });
      // 2. 提示框的位置
      const rect = el.getBoundingClientRect();
      tooltip.style.top = `${rect.bottom + window.scrollY + 5}px`;
      tooltip.style.left = `${rect.left + window.scrollX}px`;
      tooltip.className = "my-tooltip";
      document.body.appendChild(tooltip);
      el._tooltip = tooltip; // 保存引用，方便后面移除
    };
    const hideTooltip = () => {
      if (el._tooltip) {
        document.body.removeChild(el._tooltip);
        el._tooltip = null;
      }
    };
    el.addEventListener("mouseenter", showTooltip);
    el.addEventListener("mouseleave", hideTooltip);
  },
  getSSRProps(binding) {
    return {
      // SSR 期间没有DOM操作，所以这里只返回一个 title 属性
      title: binding.value,
    };
  },
};
</script>
